/*
 * @Description: 
 * @ComposerRequire: 
 * @ComposerRemove: 
 * @Author: 阿海 <764882431@qq.com>
 * @Date: 2020-12-29 10:51:13
 * @LastEditTime: 2021-07-09 15:00:21
 * @LastEditors: 阿海
 */
function Request(config){
    var resultObj = new Object;
    config = typeof(config) == 'undefined'?{}:config;
    resultObj.request_url = typeof(config.request_url) == 'undefined'?'':config.request_url;//当前请求的url
    resultObj.async = false;//同步请求 同步|异步 false|true 默认是false 同步
    resultObj.server = window.location.protocol+"//"+window.location.host;//请求的主域名域名
    resultObj.token_url =  typeof(config.token_url) == 'undefined'?'':config.token_url; //获取token的路由
    resultObj.headers = typeof(config.headers) == 'undefined'?{}:config.headers;//请求时的header
    resultObj.tokenObj = typeof(config.tokenObj) == 'undefined'?{}:config.tokenObj; //请求时的token
    resultObj.expire_time =  typeof(config.expire_time) == 'undefined'?7000:config.expire_time;  //token过期更新时间
    resultObj.token_store_name =  typeof(config.token_store_name) == 'undefined'?'request_api_token':config.token_store_name; //存储token的键名
    resultObj.isIe = function() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
        var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
        var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
        var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
        if(isIE) {
            var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
            reIE.test(userAgent);
            var fIEVersion = parseFloat(RegExp["$1"]);
            if(fIEVersion == 7) {
                return 7;
            } else if(fIEVersion == 8) {
                return 8;
            } else if(fIEVersion == 9) {
                return 9;
            } else if(fIEVersion == 10) {
                return 10;
            } else {
                return 6;//IE版本<=7
            }   
        } else if(isEdge) {
            return 'edge';//edge
        } else if(isIE11) {
            return 11; //IE11  
        }else{
            return -1;//不是ie浏览器
        }
    }

    if(resultObj.isIe == 7 || resultObj.isIe == 8 || resultObj.isIe == 9 || resultObj.isIe == 10 ){
        console.log("IE版本过低,建议升级IE浏览器");
    }
   
    //只是对get post的封装
    var request = function (method,url,data,headers,async){
          
            //初始化返回结果数据
            var result = '{"code":"3","msg":"请求异常！"}'; 

            //步骤一:创建异步对象
            var ajax = new XMLHttpRequest();
            
            //未设置url,读取默认的url
            if(!url && resultObj.request_url){
                url = resultObj.request_url;
            }

            
            if(typeof(url) != 'string'){
                console.log("URL::"+url);
                result = '{"code":"3","msg":"请求连接必须是字符串！"}';
                return JSON.parse(result);
            }

            if(!url){
                result = '{"code":"3","msg":"缺少请求的url参数！"}';
                return JSON.parse(result);
            }
          
            //get 请求 处理data
            if (data && method=='get') {
            url +='?';
            for(var item in data){
                url += item+"="+data[item]+"&";
            }
            url = url.substr(0,url.length-1);
            }

            if(async == undefined || async == ''){
                async = resultObj.async;
            }

            //开始-发起请求
            ajax.open(method,url,async);

            //重置请求时--自定义的header
            if(headers){
                for(var item in headers){
                    resultObj.headers.item = headers[item];
                }
            }
         
            //设置header
            for(var item in resultObj.headers){
                ajax.setRequestHeader(item,resultObj.headers.item == undefined?resultObj.headers[item]:'no '+item);
            }
            
            //步骤三:注册事件 onreadystatechange 状态改变就会调用
            ajax.onreadystatechange = function () {  
                //步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的　　　
                if (ajax.readyState==4 && ajax.status==200) {
                        result = ajax.responseText;
                    }
            
            }

            //步骤四:发送请求 post 处理 data数据
            if(method == 'post' && data){
                // var params = "";
                // for(var item in data){
                //     params += item+"="+data[item]+"&";  //不能使用
                // }
                // params = params.substr(0,params.length-1);
                //通过FormData构造函数创建一个空对象
                var formdata=new FormData();
                //可以通过append()方法来追加数据
                for(var item in data){
                    formdata.append(item,data[item]);
                }
                ajax.send(formdata);
            }else{
                //get 
                ajax.send();
            }
            
            try {
                return JSON.parse(result);
            }catch(e){
                return result;
            }
        }

    var init = function(){
        
        if((store.get(resultObj.token_store_name) === undefined)|| ((store.get(resultObj.token_store_name) !== undefined) && store.get(resultObj.token_store_name).iat + resultObj.expire_time < (new Date().getTime() / 1000))){
        
            if(resultObj.token_url !== ''){
                var res = request('get',resultObj.token_url);
                if (res.code == 0) {
                    resultObj.tokenObj = res.data; 
                    store.set(resultObj.token_store_name, res.data);   
                }
            }
      
        }else{
            resultObj.tokenObj = store.get(resultObj.token_store_name);
        }
    
        resultObj.headers = {
            token:((resultObj.tokenObj === undefined || resultObj.tokenObj.token === undefined)?'Token missing':resultObj.tokenObj.token),
            iss:((resultObj.tokenObj === undefined || resultObj.tokenObj.iss === undefined)?'ahai574':resultObj.tokenObj.iss),
            sub:((resultObj.tokenObj === undefined || resultObj.tokenObj.sub === undefined)?'api-token':resultObj.tokenObj.sub),
            iat:((resultObj.tokenObj === undefined || resultObj.tokenObj.iat === undefined)?new Date().getTime().toString():resultObj.tokenObj.iat),
            ip:((resultObj.tokenObj === undefined || resultObj.tokenObj.ip === undefined)?resultObj.server:resultObj.tokenObj.ip),
            aud:((resultObj.tokenObj === undefined || resultObj.tokenObj.aud === undefined)?'1993-'+(new Date()).getFullYear():resultObj.tokenObj.aud),
            id:((resultObj.tokenObj === undefined || resultObj.tokenObj.id === undefined)?resultObj.server:resultObj.tokenObj.id),
            appid:((resultObj.tokenObj === undefined || resultObj.tokenObj.appid === undefined)?resultObj.server:resultObj.tokenObj.appid),
            secret:((resultObj.tokenObj === undefined || resultObj.tokenObj.secret === undefined)?resultObj.server :resultObj.tokenObj.secret)
        }
    };

  init();

    
  resultObj.request = request;
  
  return resultObj;
}